package com.ruoyi.web.controller.net;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.net.domain.ElementProtectGroup;
import com.ruoyi.net.domain.NetElement;
import com.ruoyi.net.netconf.Device;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.IElementProtectGroupService;
import com.ruoyi.net.service.INetElementService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.net.domain.ElementPortMtnFg;
import com.ruoyi.net.service.IElementPortMtnFgService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 网元-接口-mtnfg接口Controller
 * 
 * @author net
 * @date 2024-11-17
 */
@Api(tags = "网元-接口-mtnfg接口")
@RestController
@RequestMapping("/element/port/mtn/fg")
public class ElementPortMtnFgController extends BaseController {
    @Autowired
    private IElementPortMtnFgService elementPortMtnFgService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private DeviceManager deviceManager;

    @Autowired
    private IElementProtectGroupService elementProtectGroupService;


    @ApiOperation(value = "读取网元-接口-mtnfg接口列表 init", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:fg:list')")
    @GetMapping("/init")
    public AjaxResult init(ElementPortMtnFg elementPortMtnFg) {
        elementPortMtnFgService.init(elementPortMtnFg);
        return AjaxResult.success();
    }

    /**
     * 读取网元-接口-mtnfg接口列表
     */
    @ApiOperation(value = "读取网元-接口-mtnfg接口列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:fg:list')")
    @GetMapping("/read")
    public TableDataInfo read(ElementPortMtnFg elementPortMtnFg) {
        List<ElementPortMtnFg> elementPortMtnFgs = new ArrayList<>();
        StringBuilder xml = new StringBuilder();
        xml.append(
                "<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                        "    <interfaces>" +
                        "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                        "        <type>MTN-FGPHY</type>" +
                        "        <enabled>enable</enabled>" +
                        "      </interface>" +
                        "    </interfaces>" +
                        "  </if>");
        NetElement netElement = netElementService.getCacheObject(elementPortMtnFg.getElementId());
        if (sysConfigService.selectDebugEnabled()) {
            deviceManager.getDevice(netElement.getIp());
            String rpcReply = deviceManager.getConfig(xml.toString());

            // 解析xml
            NodeList list = findNetConfXmlNodes(rpcReply, "//interfaces/interface");
            if (list != null && list.getLength() > 0) {
                for (int i = 0; i < list.getLength(); i++) {
                    ElementPortMtnFg entity = new ElementPortMtnFg();
                    Node node = list.item(i);
                    // 通过标签名获取节点的值
                    entity.setTerminalName(getXmlLabelValue(node, "name"));
                    entity.setTerminalEnable(getXmlLabelValue(node, "enabled"));
                    entity.setTerminalDesc(getXmlLabelValue(node, "description"));
                    Node flexeclientNode = getXmlLabelNode(node, "flexeclient-ctrlinterface");
                    entity.setProtectGroup(getXmlLabelValue(flexeclientNode, "fg-board-group"));
                    entity.setAccessMode(getXmlLabelValue(flexeclientNode, "calendar-mode"));
                    entity.setLowLatencyMode(getXmlLabelValue(flexeclientNode, "low-latency-mode"));
                    entity.setStatus("1"); // 从设备读取到的配置，设置状态为激活

                    elementPortMtnFgs.add(entity);
                }
            }
        }
        startPage();
        return getDIYPageTable(elementPortMtnFgs);
    }

    /**
     * 查询网元-接口-mtnfg接口列表
     */
    @ApiOperation(value = "查询网元-接口-mtnfg接口列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:fg:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElementPortMtnFg elementPortMtnFg) {
        startPage();
        List<ElementPortMtnFg> list = elementPortMtnFgService.selectElementPortMtnFgList(elementPortMtnFg);
        return getDataTable(list);
    }

    /**
     * 导出网元-接口-mtnfg接口列表
     */
    @ApiOperation(value = "导出网元-接口-mtnfg接口列表", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:fg:export')")
    @Log(title = "网元-接口-mtnfg接口", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElementPortMtnFg elementPortMtnFg) {
        List<ElementPortMtnFg> list = elementPortMtnFgService.selectElementPortMtnFgList(elementPortMtnFg);
        ExcelUtil<ElementPortMtnFg> util = new ExcelUtil<ElementPortMtnFg>(ElementPortMtnFg.class);
        util.exportExcel(response, list, "网元-接口-mtnfg接口数据");
    }

    /**
     * 获取网元-接口-mtnfg接口详细信息
     */
    @ApiOperation(value = "获取网元-接口-mtnfg接口详细信息", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:fg:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(elementPortMtnFgService.selectElementPortMtnFgById(id));
    }

    /**
     * 新增网元-接口-mtnfg接口
     */
    @ApiOperation(value = "新增网元-接口-mtnfg接口", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:fg:add')")
    @Log(title = "网元-接口-mtnfg接口", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElementPortMtnFg elementPortMtnFg) {
        return toAjax(elementPortMtnFgService.insertElementPortMtnFg(elementPortMtnFg));
    }

    /**
     * 修改网元-接口-mtnfg接口
     */
    @ApiOperation(value = "修改网元-接口-mtnfg接口", httpMethod = "PUT")
    //    @PreAuthorize("@ss.hasPermi('system:fg:edit')")
    @Log(title = "网元-接口-mtnfg接口", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElementPortMtnFg elementPortMtnFg) {
        return toAjax(elementPortMtnFgService.updateElementPortMtnFg(elementPortMtnFg));
    }

    /**
     * 删除网元-接口-mtnfg接口
     */
    @ApiOperation(value = "删除网元-接口-mtnfg接口", httpMethod = "DELETE")
    //    @PreAuthorize("@ss.hasPermi('system:fg:remove')")
    @Log(title = "网元-接口-mtnfg接口", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(elementPortMtnFgService.deleteElementPortMtnFgByIds(ids));
    }

    /**
     * 激活设备
     *
     * @param id
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @GetMapping(value = "/activate/{id}")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    public AjaxResult activateDevice(@PathVariable("id") String id) {
        ElementPortMtnFg elementPortMtnFg = elementPortMtnFgService.selectElementPortMtnFgById(id);
        elementPortMtnFg.setStatus("1");
        if (sendXml(elementPortMtnFg)) {
            return toAjax(elementPortMtnFgService.updateElementPortMtnFg(elementPortMtnFg));
        } else {
            return AjaxResult.error("激活设备失败");
        }
    }

    /**
     * 去激活设备
     *
     * @param id
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @Log(title = "去激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/unactivate/{id}")
    public AjaxResult unactivateDevice(@PathVariable("id") String id) {
        ElementPortMtnFg elementPortMtnFg = elementPortMtnFgService.selectElementPortMtnFgById(id);
        elementPortMtnFg.setStatus("0");
        if (sendXml(elementPortMtnFg)) {
            return toAjax(elementPortMtnFgService.updateElementPortMtnFg(elementPortMtnFg));
        } else {
            return AjaxResult.error("去激活设备失败");
        }
    }

    /**
     * 发送xml到设备
     *
     * @param entity
     */
    private boolean sendXml(ElementPortMtnFg entity) {
        // TODO: 2024/12/21 待与设备联调
        boolean isSend = false;
        StringBuilder xml = new StringBuilder();

        if ("1".equals(entity.getStatus())) {
            xml.append("<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                    "    <interfaces>" +
                    "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                    "        <name>" + entity.getTerminalName() + "</name>" +
                    "        <type>MTN-FGPHY</type>" +
                    "        <enabled>enable</enabled>");
            if (StringUtils.isNotEmpty(entity.getTerminalDesc())) {
                xml.append("        <description>" + entity.getTerminalDesc() + "</description>");
            }
            xml.append("        <mtn-fgphy-ctrlinterface xmlns=\"http://fiberhome.com/fhnw/yang/interface/mtninterface/fos-mtnif-fgphy\">" +
                    "          <port-laser-startup-delay-time>0</port-laser-startup-delay-time>");
            if (StringUtils.isNotEmpty(entity.getAccessMode())) {
                xml.append("          <calendar-mode>static</calendar-mode>");//静态=static
            }
            //参照2.6日志 、文档
            //需先配置细粒度业务盘保护
            if (StringUtils.isNotEmpty(entity.getProtectGroup())) {
                xml.append("          <fg-board-group>" + entity.getProtectGroup() + "</fg-board-group>");
            }
            if (StringUtils.isNotEmpty(entity.getHoldMilliseconds())) {
                xml.append("          <up-holdtime>" + entity.getHoldMilliseconds() + "</up-holdtime>");
            }
            xml.append("          <down-holdtime>0</down-holdtime>" +
//                    "          <energy-saving-mode>disable</energy-saving-mode>" +
                    "        </mtn-fgphy-ctrlinterface>" +
                    "      </interface>" +
                    "    </interfaces>" +
                    "  </if>");
        } else {

            xml.append("<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                    "    <interfaces>" +
                    "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                    "        <name>" + entity.getTerminalName() + "</name>" +
                    "        <type>MTN-FGPHY</type>" +
                    "        <enabled>enable</enabled>");
            if (StringUtils.isNotEmpty(entity.getTerminalDesc())) {
                xml.append("        <description>" + entity.getTerminalDesc() + "</description>");
            }
            xml.append("        <mtn-fgphy-ctrlinterface xmlns=\"http://fiberhome.com/fhnw/yang/interface/mtninterface/fos-mtnif-fgphy\">" +
                    "          <port-laser-startup-delay-time nc:operation=\"remove\">0</port-laser-startup-delay-time>");
            if (StringUtils.isNotEmpty(entity.getAccessMode())) {
                xml.append("          <calendar-mode nc:operation=\"remove\">static</calendar-mode>");
            }
            if (StringUtils.isNotEmpty(entity.getHoldMilliseconds())) {
                xml.append("          <up-holdtime nc:operation=\"remove\">" + entity.getHoldMilliseconds() + "</up-holdtime>");
            }
            xml.append("          <down-holdtime nc:operation=\"remove\">0</down-holdtime>" +
                    "          <energy-saving-mode>disable</energy-saving-mode>" +
                    "        </mtn-fgphy-ctrlinterface>" +
                    "      </interface>" +
                    "    </interfaces>" +
                    "  </if>");
        }
//        xml.append("<fgboard-grp xmlns=\"http://fiberhome.com/fhnw/yang/protectgroup/fos-fgboardgroup\">" +
//                "    <fg-board-group-cfgs>" +
//                "    <fg-board-group-cfg nc:operation=\"" + operation + "\">" +
//                "        <fg-board-group-index>" + elementProtectGroup.getGroupId() + "</fg-board-group-index>" +
//                "        <member-slot-list>" +
//                "          <slot-num>" + elementProtectGroup.getBusId() + "</slot-num>" + // 0/1/0
//                "        </member-slot-list>" +
//                "      </fg-board-group-cfg>" +
//                "    </fg-board-group-cfgs>" +
//                "  </fgboard-grp>");
        logger.info("MTN FG接口激活xml为：{}", xml);
        NetElement netElement = netElementService.getCacheObject(entity.getElementId());
        Device device = deviceManager.getDevice(netElement.getIp());
        if (device.isConnected()) {
            isSend = deviceManager.editConfig(xml.toString(), "merge");
        }
        return isSend;
    }
}